package com.yupi.yuojcodesandbox.sandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.StatsCmd;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.yupi.yuojcodesandbox.factory.CodeSandbox;
import com.yupi.yuojcodesandbox.model.ExecuteCodeRequest;
import com.yupi.yuojcodesandbox.model.ExecuteCodeResponse;
import com.yupi.yuojcodesandbox.model.ExecuteMessage;
import com.yupi.yuojcodesandbox.model.JudgeInfo;
import com.yupi.yuojcodesandbox.sandbox.java.JavaDockerCodeSandbox;
import com.yupi.yuojcodesandbox.threads.TimeManagerThread;
import com.yupi.yuojcodesandbox.utils.LanguageCmdUtils;
import com.yupi.yuojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author yuhao
 */
@Slf4j
public abstract class AbstractDockerCodeSandbox implements CodeSandbox {

    private static final long TIME_OUT = 5000L;

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    /**
     * 不同语种的挂载路径
     */
    private final String mountPath;
    /**
     * 镜像名称
     */
    private final String image;
    /**
     * 不同语种与docker交互的命令
     */
    private final String languageCmd;

    private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR;



    static {
        THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
                50,
                50 * 2,
                60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }
    public AbstractDockerCodeSandbox(String image, String languageCmd, String mountPath) {
        this.image = image;
        this.languageCmd = languageCmd;
        this.mountPath = mountPath;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        JavaDockerCodeSandbox javaDockerCodeSandbox = new JavaDockerCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafeCode/RunFileError.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaDockerCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);


    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) throws ExecutionException, InterruptedException {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        //1. 把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);
        //2. 编译代码，得到 class 文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile,language);
        // 3. 执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);
        // 4. 收集整理输出结果
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessageList);
        // 5. 文件清理
        boolean b = deleteFile(userCodeFile);
        if (!b) {
            log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
        }
        return outputResponse;
    }


    /**
     * 1. 把用户的代码保存为文件
     * @param code 用户代码
     * @return
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        // 把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        return FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
    }

    /**
     * 2、编译代码
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile,String language) {
        try {
            String compileCMD = LanguageCmdUtils.getCompileCmd(userCodeFile.getAbsolutePath(), language,mountPath);
            Process compileProcess = Runtime.getRuntime().exec(compileCMD);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if (executeMessage.getExitValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
//            return getErrorResponse(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 4、获取输出结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        // 要借助第三方库来获取内存占用，非常麻烦，此处不做实现
//        judgeInfo.setMemory();
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }
    /**
     * 5、删除文件
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            System.out.println("用户代码临时存放路径"+userCodeParentPath);
            return FileUtil.del(userCodeParentPath);
        }
        return true;
    }
    /**
     * 6、获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }


    /**
     * 3、创建容器，把文件复制到容器内
     *
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList){
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        // 获取默认的 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        // 创建容器
        CreateContainerResponse container = createContainer(dockerClient, userCodeParentPath,image);
        String containerId = container.getId();
        // 启动容器  目前来说 容器已经运行 可以与之交互了
        dockerClient.startContainerCmd(containerId).exec();
        // docker exec keen_blackwell java -cp /app Main 1 3
        // 执行命令并获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        List<Future<ExecuteMessage>> futureLists = new ArrayList<>();
        try {
            for (String inputArgs : inputList) {
                Future<ExecuteMessage> future = THREAD_POOL_EXECUTOR.submit(() -> {
                    // 执行测试用例并与 Docker 交互
                    StopWatch stopWatch = new StopWatch();
                    // 创建容器终端
                    long time = 0L;
                    final long[] maxMemory = {0L};
                    // 获取占用的内存
                    StatsCmd statsCmd = dockerClient.statsCmd(containerId);
                    ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(createMemoryStatisticResultCallback(maxMemory));
                    statsCmd.exec(statisticsResultCallback);
                    // 记录用户代码执行时间
                    stopWatch.start();
                    //构建java命令 docker exec -it containerId java -cp /app Main
                    Process process = Runtime.getRuntime().exec(String.format(languageCmd, containerId, mountPath));
                    //控制用户代码执行超时的线程
                    TimeManagerThread timeManagerThread =  new TimeManagerThread(TIME_OUT);
                    timeManagerThread.setProcess(process);
                    timeManagerThread.start();
                    // ACM模式向控制台种输入数据
                    ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(process, inputArgs);
                    stopWatch.stop();
                    time = stopWatch.getLastTaskTimeMillis();
                    statsCmd.close();
                    executeMessage.setTime(time);
                    executeMessage.setMemory(maxMemory[0]);
                    return executeMessage;
                });
                futureLists.add(future);
            }
//            按照任务提交的顺序  收集结果  便于后续比较测试用例的 输出结果和 db中的正确结果是否一致（按序比较）
            for (Future<ExecuteMessage> future : futureLists) {
                ExecuteMessage executeMessage = future.get();
                executeMessageList.add(executeMessage);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            dockerClient.stopContainerCmd(containerId).exec();
            dockerClient.removeContainerCmd(containerId).withForce(true).exec();
            try {
                dockerClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return executeMessageList;
    }


    private ResultCallback<Statistics> createMemoryStatisticResultCallback(long[] maxMemory) {
        return new ResultCallback<Statistics>() {
            @Override
            public void onNext(Statistics statistics) {
                Long usage = statistics.getMemoryStats().getUsage();
                maxMemory[0] = Math.max(Optional.ofNullable(usage).orElse(0L), maxMemory[0]);
                System.out.println("内存使用：" + maxMemory[0]);
            }

            @Override
            public void close() throws IOException {

            }

            @Override
            public void onStart(Closeable closeable) {

            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        };
    }

    private ExecStartResultCallback createExecStartResultCallback(boolean[] timeout, String[] message, String[] errorMessage) {
        ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
            @Override
            public void onComplete() {
                // 如果执行完成，则表示没超时
                timeout[0] = false;
                super.onComplete();
            }

            @Override
            public void onNext(Frame frame) {
                StreamType streamType = frame.getStreamType();
                if (StreamType.STDERR.equals(streamType)) {
                    errorMessage[0] = new String(frame.getPayload());
                    System.out.println("输出错误结果：" + errorMessage[0]);
                } else {
                    message[0] = new String(frame.getPayload());
                    System.out.println("输出结果：" + message[0]);
                }
                super.onNext(frame);
            }
        };
        return execStartResultCallback;

    }

    private void createContainerExec(DockerClient dockerClient, String containerId, String[] cmdArray) {
        ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                .withCmd(cmdArray)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .exec();
    }

    private ExecCreateCmdResponse createContainerExec(DockerClient dockerClient, String containerId) {
        return dockerClient.execCreateCmd(containerId)
                .withCmd("/bin/bash")
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .exec();
    }

    private CreateContainerResponse createContainer(DockerClient dockerClient, String userCodeParentPath, String image) {

        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        CreateContainerResponse containerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        return containerResponse;
    }

}



